<template>
  <div class="commodity">
    <topside></topside>
    <div class="commodity_home">
      <!-- 图片展示 -->
      <div class="images">
        <div class="img">
          <img src="../assets/img/6花.jpg" alt="">
        </div>
        <div class="imgs">
          <img src="../assets/img/6花.jpg" alt="">
          <img src="../assets/img/6花.jpg" alt="">
          <img src="../assets/img/6花.jpg" alt="">
          <img src="../assets/img/6花.jpg" alt="">
          <img src="../assets/img/6花.jpg" alt="">
          <img src="../assets/img/6花.jpg" alt="">
        </div>
      </div>
      <!-- 商品参数 -->
      <div class="commodity_particulars">
        <div class="top">
          <div>{{commodity.categoryName}}</div>
          <div>{{commodity.categorySlogan}}</div>

          <div>月销5000</div>
          <div><span>￥</span>{{itemObj.minPrice ? itemObj.minPrice : obj.minPrice}}</div>
        </div>
        <div class="home">
          <div class="home_left">
            规格分类：
          </div>
          <div class="home_right">
            <!-- 商品参数 -->
            <div class="home_right_item" :class="{'home_right_item_click':isChoose==index}" v-for="(item,index) in commodity.productSkuList" :key="index" @click="item_click(item,index)">
              <img :src="'http://43.138.33.247/' + item.skuImg" alt="">
              <span>{{item.skuName}}</span>
            </div>
          </div>
        </div>
        <div class="home">
          <div class="home_left">
            口味分类：
          </div>
          <div class="home_right">
            <!-- 商品参数 -->
            <div class="home_right_item" :class="{'home_right_item_click':isSkuChoose==index}" v-for="(item,index) in skuPropsItem" :key="index" @click="skuitem_click(item,index)">
              <span>{{item}}</span>
            </div>
          </div>
        </div>
        <div class="botton">
          <el-input-number v-model="num" :min="1" :max="10" label="描述文字"></el-input-number>
          <button @click="add_shopping">加入购物车</button>
          <button @click="add_buy">点击购买</button>
        </div>
      </div>
    </div>

    <el-dialog :visible.sync="dialogTableVisible" :show-close="false">
      <div class="dialog_btn">
        <div class="_address_content" v-if="!TopNavAddress.length == 0">
          <AddressDescriptions :TopNavAddress="TopNavAddress"></AddressDescriptions>
        </div>
        <div id="qrcode" ref="qrcode"></div>
        <el-button type="success">微信支付</el-button>
        <el-button type="primary">支付宝支付</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCommodity, postAddShopping, getUserAddress, postBuy } from '../config/api'
import topside from '../components/topside'
import AddressDescriptions from '../components/AddressDescriptions'

import { Base64 } from 'js-base64'

// 引入二维码库
import QRCode from 'qrcodejs2'

export default {
  data() {
    return {
      size: '',
      // 保存的商品的id
      commodityId: 0,
      // 保存的商品详情信息
      commodity: {},
      // 保存口味规格的数组
      skuPropsItem: [],
      // item
      obj: {
        minPrice: 0 // 初始售卖价格
      },
      itemObj: {},
      num: 1, //  计数器
      // 控制item列表的样式
      isChoose: null,
      // 控制规格item列表的样式
      isSkuChoose: null,
      // 解密得到token
      Base64: require('js-base64').Base64,
      token: Base64.decode(window.localStorage.getItem('shopping_token')),
      // 用于加入购物车的信息
      shopping_: {
        productId: '', // 商品规格id
        skuId: '', // 套餐id
        userId: window.localStorage.getItem('userId'), // 用户id
        cartNum: '', // 商品的购买数量
        productPrice: '', // 商品价格
        skuProps: '' // 商品口味
      },
      // 收货地址数据
      TopNavAddress: [],
      dialogTableVisible: false
    }
  },
  components: {
    topside,
    AddressDescriptions
  },
  methods: {
    shoppingCount() {
      this.shopping_.cartNum = String(this.num) // 购买数量
      this.shopping_.userId = window.localStorage.getItem('userId') // 用户id
      this.shopping_.skuProps = this.skuPropsItem[this.isSkuChoose] // 口味
      this.shopping_.skuId = this.commodity.productSkuList[this.isSkuChoose].skuId // 套餐id
      this.shopping_.productId = this.commodity.productSkuList[this.isSkuChoose].productId // 商品规格id
      this.shopping_.productPrice = String(this.commodity.productSkuList[this.isSkuChoose].sellPrice) // 打折优惠过的价格
    },
    // 加入购物车
    add_shopping() {
      // if (window.localStorage.getItem('userId') == null) return this.$message.error('请先登录')
      this.$isExistUser()

      if (this.isChoose == null) return this.$message.error('请选择参数')
      if (this.isSkuChoose == null) return this.$message.error('请选择口味')
      this.shoppingCount()

      // console.log(JSON.stringify(this.shopping_))
      postAddShopping(this.token, this.shopping_)
        .then(result => {
          if (result.status == 200) {
            if (result.data.code == 200) {
              this.$message({
                showClose: true,
                message: '加入购物车成功！',
                type: 'success'
              })
            }
          }
        })
        .catch(err => {
          console.log(err)
          if (err) {
          }
          this.$message.error('添加购物车失败')
        })
    },
    // 立即购买
    add_buy() {
      // if (window.localStorage.getItem('userId') == null) return this.$message.error('请先登录')
      this.$isExistUser()
      if (this.isChoose == null) return this.$message.error('请选择参数')
      if (this.isSkuChoose == null) return this.$message.error('请选择口味')

      this.dialogTableVisible = true
      this.shoppingCount()
      let orders = {
        actualAmount: Number(this.shopping_.productPrice), //  商品实际支付价格
        cancelTime: '',
        closeType: 0,
        createTime: '',
        deleteStatus: 0,
        deliveryFlowId: '',
        deliveryTime: '',
        deliveryType: '',
        flishTime: '',
        orderFreight: 0,
        orderId: '',
        orderRemark: '订单备注', //订单备注
        payTime: '',
        payType: 1, //支付方式 1：微信 2：支付宝
        receiverAddress: this.TopNavAddress[0].province + this.TopNavAddress[0].city + this.TopNavAddress[0].area + this.TopNavAddress[0].addr, // 收货地址
        receiverMobile: this.TopNavAddress[0].receiverMobile, //收货人手机号
        receiverName: this.TopNavAddress[0].receiverName, // 收货人
        status: '',
        totalAmount: 200, // 原价支付价格
        untitled: '',
        updateTime: '',
        userId: this.shopping_.userId //用户ID
      }
      postBuy(this.token, this.shopping_.productId, this.shopping_.skuId, this.num, orders)
        .then(result => {
          if (result.status == 200) {
            if (result.data.code == 200) {
              console.log(result.data.data)
              this.$nextTick(() => {
                this.$refs.qrcode.innerHTML = ''

                new QRCode('qrcode', {
                  width: 150, //宽度
                  height: 150, // 高度
                  text: result.data.data.payUrl, // 二维码内容
                  render: 'canvas',
                  correctLevel: QRCode.CorrectLevel.H
                })

                let url = 'ws://localhost:3000/webSocket/' + result.data.data.productOrderId
                console.log(url)

                let webSocket = new WebSocket(url)
                console.log(webSocket)
                webSocket.onmessage = function (event) {
                  var msg = event.data
                  console.log(msg)
                  if ('1' == msg) {
                    this.status = msg
                    alert('付款成功！！！！')
                    window.location.href = 'order.html'
                  }
                }
              })
            }
          }
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 点击规格参数项
    skuitem_click(item, index) {
      if (index == this.isSkuChoose) {
        this.isSkuChoose = null
        // 移除参数
        this.shopping_.skuProps = ''
      } else {
        this.isSkuChoose = index
        // 保存参数
        this.shopping_.skuProps = this.skuPropsItem[index]
      }
    },
    // 点击商品项
    item_click(item, index) {
      this.itemObj.minPrice = this.commodity.productSkuList[index].originalPrice
      if (index == this.isChoose) {
        this.isChoose = null
        this.itemObj.minPrice = null
      } else {
        this.isChoose = index
      }
    },
    getcat() {
      getCommodity(this.commodityId)
        .then(result => {
          if (result.status == 200) {
            console.log(result.data.data[0])
            this.commodity = result.data.data[0]
            let minPrice = 999999999999
            let productSkuList = result.data.data[0].productSkuList
            for (let i = 0; i < productSkuList.length; i++) {
              if (minPrice > productSkuList[i].originalPrice) {
                minPrice = productSkuList[i].originalPrice
                // 得到规格字符串数组参数
                const regex = /\[(.+?)\]/g
                this.skuPropsItem = JSON.parse(productSkuList[i].untitled.match(regex)[0])
              }

              if (i == result.data.data[0].productSkuList.length - 1) {
                this.obj.minPrice = minPrice
              }
            }
          }
        })
        .catch(err => {
          console.log(err)
        })
    }
  },
  mounted() {
    getUserAddress(this.token, this.shopping_.userId)
      .then(result => {
        if (result.status == 200) {
          if (result.data.code == 200) {
            this.TopNavAddress = result.data.data
          }
          console.log(result)
          if (result.data.code == 404) {
            this.$message.error('登录过期，请重新登录')
            // this.top_nav_btn_exit()
            // this.top_nav_btn_login()
          }
        }
      })
      .catch(err => {
        console.log(err)
      })
  },
  created() {},
  beforeRouteEnter(to, from, next) {
    if (to.query.commodityItemId != '') {
      next(vm => {
        vm.commodityId = Number(to.query.commodityItemId)
        vm.getcat()
      })
    } else {
      next('/home')
    }
  }
}
</script>

<style lang="less" scoped>
.commodity {
  .commodity_home {
    display: flex;
    width: 100%;
    padding: 0px calc((100vw - 1200px) / 2);
    // 商品图片
    .images {
      display: flex;
      flex-direction: column;
      .img {
        img {
          width: 400px;
          height: 400px;
        }
      }
      .imgs {
        display: flex;
        justify-content: space-between;
        width: 400px;

        img {
          width: 50px;
          height: 60px;
        }
      }
    }
    // 商品参数
    .commodity_particulars {
      .top {
      }
      .home {
        display: flex;
        .home_left {
        }
        .home_right {
          width: 400px;
          .home_right_item {
            cursor: pointer;
            img {
            }
            span {
            }
          }
          .home_right_item_click {
            border: 2px solid #000;
          }
        }
      }
      .botton {
      }
    }
  }
  // 更改dialog样式
  .el-dialog__wrapper {
    /deep/.el-dialog {
      .el-dialog__header {
        padding: 0px;
      }
      .el-dialog__body {
        padding: 20px 20px;
      }
    }
  }
}
</style>